from pandas import read_csv
from pandas import datetime
from pandas import DataFrame
from pandas import concat
from matplotlib import pyplot
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from keras.utils.vis_utils import plot_model
import numpy as np


def mean_absolute_percentage_error(y_true, y_pred):
    # 平均绝对百分比误差（MAPE）的计算
    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100

def parser(x):
    return datetime.strptime('190'+x, '%Y-%m')

# persistence model
def model_persistence(x):
    return x


if __name__ == '__main__':

    series = read_csv(
        'E:\lyf_ML_Drought\coding\ML_Drought_Prediction\indices_caculate\\result\ROW_SPEI\ROW_SPEI-12\SPEI-12_52533.txt',
        header=None, names=('TIME', 'SPEI-1'))
    series = series.set_index(['TIME'], drop=True)  # 把日期作为索引
    # Create lagged dataset
    values = DataFrame(series.values)
    dataframe = concat([values.shift(1), values], axis=1)
    dataframe.columns = ['t-1', 't']

    # split into train and test sets
    X = dataframe.values
    train_size = int(len(X) * 0.90)
    train, test = X[1:train_size], X[train_size:]
    train_X, train_y = train[:,0], train[:,1]
    test_X, test_y = test[:,0], test[:,1]

    # walk-forward validation
    predictions = list()
    for x in test_X:
        yhat = model_persistence(x)
        predictions.append(yhat)
    # test_score = mean_squared_error(test_y, predictions)
    # print('Test MSE: %.3f' % test_score)
    print("predict rmse: ", np.sqrt(mean_squared_error(test_y, predictions)))
    print("predict mae: ", mean_absolute_error(test_y, predictions))
    print("predict mape: ", mean_absolute_percentage_error(test_y, predictions))
    print("predict r2: ", r2_score(test_y, predictions))

    # plot predictions and expected results
    # pyplot.plot(train_y)
    pyplot.plot([x for x in test_y])
    pyplot.plot([x for x in predictions])
    pyplot.show()